package net.tp.algo.graph;

import java.util.*;

/**
 *
 * @author Trung Phan
 */
public class TopologicalSort {

    public static List<Integer> sort(Graph graph) {

        int N = graph.order();

        List<Integer> result = new ArrayList<>();

        boolean[] marked = new boolean[N];

        for (int s : graph.vertices()) {
            if (!marked[s]) {
                marked[s] = true;

                Stack<Integer> stack = new Stack<>();
                stack.push(s);

                while (!stack.empty()) {
                    int u = stack.pop();
                    result.add(u);

                    for (int w : graph.adjacents(u)) {
                        if (!marked[w]) {
                            marked[w] = true;
                            stack.push(w);
                        }
                    }
                }
            }
        }


        if (!valid(graph, result)) {
            return Collections.emptyList();
        }

        return result;
    }

    public static boolean valid(Graph graph, List<Integer> vertices) {

        if (vertices.size() != graph.order()) {
            return false;
        }

        Set<Integer> visited = new HashSet<>();
        for (int u : vertices) {

            if (visited.contains(u)) return false;

            visited.add(u);
            for (int w : graph.adjacents(u)) {
                if (visited.contains(w)) {
                    return false;
                }
            }
        }

        return true;
    }

}
